<!-- 日常数据录入 -->
<template>
  <div class="content">
    <!-- 按名字/编号搜索 -->
    <div class="nameSearch">
      <el-input v-model="searchName" style="width: 17vw" placeholder="按编号查询（可选）" clearable>
        <template #append>
          <el-button :icon="Search" @click="screenSearchWithId" />
        </template>
      </el-input>
    </div>
    <!-- 按地址搜索 -->
    <div class="addressSearch">
      <el-col :span="13">
        <el-select v-model="selectCell" placeholder="选择单元楼" style="width: 15vw">
          <el-option v-for="item in cells" :key="item.value" :value="item.value" />
        </el-select>
        <el-select v-model="selectFloor" placeholder="选择楼层数" style="width: 15vw">
          <el-option v-for="item in floorValues" :key="item.value" :value="item.value" />
        </el-select>
        <el-select v-model="selectRoom" placeholder="选择房间号" style="width: 15vw">
          <el-option v-for="item in roomValues" :key="item.value" :value="item.value" />
        </el-select>
      </el-col>
      <el-col :span="5">
        <el-button type="primary" @click="getScreenDailyDataWithAddress">筛选</el-button>
      </el-col>
    </div>
    <!-- 日常数据录入表格 -->
    <el-table :data="tableData" style="width: 100%" @getSelectionRows="getSelectionRows">
      <el-table-column fixed prop="userId" label="编号" width="120" />
      <el-table-column prop="admissionTime" label="入院日期" width="150" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="gender" label="性别" width="120" />
      <el-table-column prop="birthdate" label="出生" width="150" />
      <el-table-column prop="bedPlace" label="床位" width="180" />
      <el-table-column fixed="right" label="编辑数据" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="openDailyDialog(scope.row)">日常数据</el-button>
          <el-button link type="primary" size="small" @click="openTijianDialog(scope.row)">
            体检数据
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 编辑日常数据弹窗 -->
    <div class="editDialog">
      <el-dialog v-model="editDataVisible" title="日常数据" width="500" align-center>
        <template #default>
          <div>编号：{{ currentUser.userId }}</div>
          <div>姓名：{{ currentUser.name }}</div>
          <div>记录时间：{{ dailyData.recordDate }}</div>

          <div class="editDialog-content">
            <div class="temperature">
              <span>体温：</span>
              <el-input v-model="dailyData.temperature" style="width: 100px" placeholder="如:37.5" />
            </div>
            <div class="psychosis">
              <span>精神状态：</span>
              <el-input v-model="dailyData.mentalState" style="width: 100px" placeholder="如:良好" />
            </div>
            <div class="weight">
              <span>体重：</span>
              <el-input v-model="dailyData.weight" style="width: 100px" placeholder="单位kg" />
            </div>
            <div class="medicine">
              <span>用药情况：</span>
              <el-input v-model="dailyData.medication" style="width: 100px" placeholder="如:无/布洛芬" />
            </div>
            <div class="heartRate">
              <span>心率：</span>
              <el-input v-model="dailyData.heartRate" style="width: 100px" placeholder="如:90" />
            </div>
          </div>
        </template>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="editDataVisible = false">取消</el-button>
            <el-button type="primary" @click="submitDailyData">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!-- 编辑体检数据弹窗 -->
    <div class="tijianDialog">
      <el-dialog v-model="tijianDialogVisible" title="体检数据" width="500" align-center>
        <template #default>
          <div>编号：{{ currentUser.userId }}</div>
          <div>姓名：{{ currentUser.name }}</div>
          <div>记录时间：{{ dailyData.recordDate }}</div>
          <div class="tijianDialog-content">

            <!-- 第一行 -->
            <div class="bloodPressure">
              <span>血压：</span>
              <el-input v-model="tijianData.bloodPressure" style="width: 100px" placeholder="如:120/80" />
            </div>
            <div class="bloodSugar">
              <span>血糖：</span>
              <el-input v-model="tijianData.bloodSugar" style="width: 100px" placeholder="如:5.6" />
            </div>

            <!-- 第二行 -->
            <div class="weight">
              <span>体重：</span>
              <el-input v-model="tijianData.weight" style="width: 100px" placeholder="单位kg" />
            </div>
            <div class="heartRate">
              <span>心率：</span>
              <el-input v-model="tijianData.heartRate" style="width: 100px" placeholder="如:90" />
            </div>

            <!-- 第三行 -->
            <div class="cholesterol">
              <span>胆固醇：</span>
              <el-input v-model="tijianData.cholesterol" style="width: 100px" placeholder="如:5.2" />
            </div>
            <div class="urineTest">
              <span>尿液检查：</span>
              <el-input v-model="tijianData.urineTest" style="width: 100px" placeholder="如:正常" />
            </div>

            <!-- 第四行 -->
            <div class="boneDensity">
              <span>骨密度：</span>
              <el-input v-model="tijianData.boneDensity" style="width: 100px" placeholder="如:1.0" />
            </div>
            <div class="visionHearing">
              <span>视力听力：</span>
              <el-input v-model="tijianData.visionHearing" style="width: 100px" placeholder="如:良好" />
            </div>

            <!-- 第五行 -->
            <div class="psychosis">
              <span>精神状态：</span>
              <el-input v-model="tijianData.mentalState" style="width: 100px" placeholder="如:良好" />
            </div>
            <div class="skinHealth">
              <span>皮肤健康：</span>
              <el-input v-model="tijianData.skinHealth" style="width: 100px" placeholder="如:正常" />
            </div>

            <!-- 第六行 -->
            <div class="stomachManagement">
              <span>肠胃管理：</span>
              <el-input v-model="tijianData.stomachManagement" style="width: 100px" placeholder="如:无不适" />
            </div>
          </div>
        </template>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="tijianDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitTijianData">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import type { Bed } from '../../API/interface/bedManagement'
import { getAllBeds } from '@/API/interface/bedManagement'
import { Search } from "@element-plus/icons-vue";
import type { UserInfo, EditDialogData, TijianDialogData, ScreenAddress } from '@/API/interface/dailyData'
import { screenDailyDataWithAddress, screenDailyDataWithId, getAllDailyData, submitDailyDataApi, submitCheckDataApi } from '@/API/interface/dailyData'
import { ElMessage } from 'element-plus'
// 获取当前行的数据
const getSelectionRows = ref<UserInfo[]>([])
const currentUser = ref<UserInfo>({
  userId: '',
  admissionTime: '',
  name: '',
  gender: '',
  birthdate: '',
  bedPlace: ''
})
// 打开日常编辑弹窗
const openDailyDialog = (row: UserInfo) => {
  currentUser.value = row
  dailyData.value = {
    elderId: row.userId, // 使用当前选中行的 userId 更新 elderId
    recordDate: new Date().toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    }).replace(/\//g, '-'),
    temperature: '',
    mentalState: '',
    weight: '',
    medication: '',
    heartRate: '',
  };
  editDataVisible.value = true
}
// 日常健康数据
const dailyData = ref<EditDialogData>({
  elderId: currentUser.value.userId,
  recordDate: new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-'),
  temperature: '',
  mentalState: "",
  weight: "",
  medication: "",
  heartRate: "",
})
// 提交日常数据
const submitDailyData = async () => {

  const res = await submitDailyDataApi(dailyData.value);
  console.log("提交的日常数据", dailyData.value);
  console.log("日常数据返回", res);
  if (res.data.code === 200) {
    ElMessage.success("提交成功");
    editDataVisible.value = false

  }

}
// 打开体检数据弹窗
const openTijianDialog = (row: UserInfo) => {
  currentUser.value = row
  tijianData.value = {
    elderId: row.userId, // 使用当前选中行的 userId 更新 elderId
    checkDate: new Date().toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    }).replace(/\//g, '-'),
    bloodPressure: "",
    bloodSugar: "",
    weight: "",
    heartRate: "",
    cholesterol: "",
    urineTest: "",
    boneDensity: "",
    visionHearing: "",
    mentalState: "",
    skinHealth: "",
    stomachManagement: "",
  }
  tijianDialogVisible.value = true
}
// 体检数据
const tijianData = ref<TijianDialogData>({
  elderId: "",
  checkDate: '',
  bloodPressure: "",
  bloodSugar: "",
  weight: "",
  heartRate: "",
  cholesterol: "",
  urineTest: "",
  boneDensity: "",
  visionHearing: "",
  mentalState: "",
  skinHealth: "",
  stomachManagement: "",
})
// 提交体检数据
const submitTijianData = async () => {
  const res = await submitCheckDataApi(tijianData.value)
  console.log('提交的体检数据', tijianData.value);
  console.log("体检数据返回", res);
  if (res.data.code === 200) {
    ElMessage.success("提交成功");
    tijianDialogVisible.value = false

  }
}
// 表格数据
const tableData = ref<UserInfo[]>([]);
const editDataVisible = ref(false);  //日常数据弹窗
const tijianDialogVisible = ref(false);  //体检数据弹窗

// 初始楼和用户编号
const allBedInfo = ref([]);  //获取所有床位信息
const filteredBedrooms = ref<Bed[]>([]); // 修正为 Bed 类型
const selectCell = ref('') //选中单元楼
const selectFloor = ref('') ///选中楼层
const selectRoom = ref('') //选中房间
const searchName = ref('')  //编号搜索
//获取所有床位信息
onMounted(async () => {
  const res = await getAllBeds();
  console.log("获取所有床位", res.data);
  allBedInfo.value = res.data.data;  //把所有床位信息存到allBedInfo里面
  console.log("allBedInfo", allBedInfo.value);
  // 将allBedInfo中的数据映射到bedrooms中
  filteredBedrooms.value = allBedInfo.value.map((bed: any) => ({
    bedId: bed.bedId,
    buildingNo: bed.buildingNo,
    roomNo: bed.roomNo,
    floorNo: bed.floorNo,
    bedNo: bed.bedNo,
    assignedUserGender: bed.status === '空' ? '' : bed.gender, // 如果床位状态为空，则分配用户为空
    price: bed.price,
  }));
  // 动态填充楼房、楼层、房间和床位信息
  const uniqueBuildings = new Set<string>();
  const uniqueFloors = new Set<string>();
  const uniqueRooms = new Set<string>();
  const uniqueBeds = new Set<string>();

  res.data.data.forEach((bed: any) => {
    uniqueBuildings.add(bed.buildingNo);
    uniqueFloors.add(bed.floorNo);
    uniqueRooms.add(bed.roomNo);
    uniqueBeds.add(bed.bedNo);
  });

  cells.value = Array.from(uniqueBuildings).map(building => ({ value: building }));
  floorValues.value = Array.from(uniqueFloors).map(floor => ({ value: floor }));
  roomValues.value = Array.from(uniqueRooms).map(room => ({ value: room }));
  bedValues.value = Array.from(uniqueBeds).map(bed => ({ value: bed }));

  // 获取所有用户数据
  const userRes = await getAllDailyData();
  console.log("获取所有用户数据", userRes.data);
  userRes.data.data.forEach((user: UserInfo) => {
    const birthdate = new Date(user.birthdate).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    }).replace(/\//g, '-');
    tableData.value.push({
      userId: user.userId,
      admissionTime: user.admissionTime,
      name: user.name,
      gender: user.gender,
      birthdate: birthdate,
      bedPlace: user.bedPlace,
    });
  })

});
const cells = ref([
  { value: '' }
]);

const floorValues = ref([
  { value: '' }
]);
const roomValues = ref([
  { value: '' }
]);
const bedValues = ref([
  { value: '' }
]);
// 根据id获取数据
const screenSearchWithId = async () => {
  const res = await screenDailyDataWithId({ userId: searchName.value })
  console.log("id返回数据", res.data.data);
  const user = res.data.data;
  tableData.value = []
  const birthdate = new Date(user.birthdate).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-');
  tableData.value.push({
    userId: user.userId,
    admissionTime: user.admissionTime,
    name: user.name,
    gender: user.gender,
    birthdate: birthdate,
    bedPlace: user.bedPlace,
  });
  searchName.value = '' // 搜索框清空
}
// 根据住址获取数据
const getScreenDailyDataWithAddress = async () => {
  const address = ref<ScreenAddress>({
    buildingNo: selectCell.value,
    floorNo: selectFloor.value,
    roomNo: selectRoom.value
  })
  console.log(address.value);

  const res = await screenDailyDataWithAddress(address.value)
  console.log("地址筛选结果", res.data);
  tableData.value = []
  res.data.data.forEach((user: UserInfo) => {
    const birthdate = new Date(user.birthdate).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    }).replace(/\//g, '-');
    tableData.value.push({
      userId: user.userId,
      admissionTime: user.admissionTime,
      name: user.name,
      gender: user.gender,
      birthdate: birthdate,
      bedPlace: user.bedPlace,
    });
  })
  // 清空输入框
  selectFloor.value = ''
  selectRoom.value = ''
  selectCell.value = ''
}
</script>

<style lang="less" scoped>
.nameSearch {
  margin: 1vh 0;
}

.addressSearch {
  display: flex;
  gap: 1vw;
}

.editDialog-content,
.tijianDialog-content {
  display: flex;
  flex-direction: row;
  gap: 2%;
  flex-wrap: wrap;

  //所有元素
  &>* {
    flex: 0 0 48%;
    max-width: 48%;
    /* 防止元素宽度超过父容器 */
    margin-top: 1vh;
  }
}
</style>